// 引入
const express = require('express');
const path = require('path');
const fs = require('fs')
const time = require('time-stamp');
const userRouter = express.Router();

// 开放静态资源
userRouter.use(express.static(path.join(__dirname, 'hhhh')));

// 渲染登录页面
userRouter.get('/login', (req, res) => {
    res.sendFile(path.join(__dirname, 'hhhh/login.html'));
})

// 渲染注册页面
userRouter.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, 'hhhh/register.html'));
})

// 接收post提交的参数
userRouter.use(express.urlencoded({ extended: false }));

// 获取所有用户信息
let per = JSON.parse(fs.readFileSync(path.join(__dirname, 'persons.json'), 'utf-8'));

// 登录判断
userRouter.post('/login', (req, res, next) => {
    user = req.body;
    let tag = per.some(item => item.username == user.username && item.password == user.password);
    if (tag) {
        res.send('登录成功');
    }
    else {
        next('账号或密码错误');
    }
})

// 注册判断
userRouter.post('/register', (req, res, next) => {
    let { username, password, password2 } = req.body;
    if (password == password2) {
        let tag = per.some(item => item.username == username);
        if (tag) {
            res.send('该用户已存在');
        }
        else {
            per.push({ username: username, password: password, time: time('YYYY年MM月DD日 HH:mm:ss') });
            fs.writeFileSync(path.join(__dirname, 'persons.json'), JSON.stringify(per))
            res.send('注册成功');
        }
    }
    else {
        next('再次输入密码错误');
    }
})

// 暴露
module.exports = userRouter;